export type StateEnum = {
	id: number
	text: string
	state: boolean
}

export type StateType = Array<StateEnum>

export type ActionType = {
	type: 'ADD' | 'DELETE' | 'CHANGE'
	listItem?: StateEnum
}

export default function listReducers(state: StateType, action: ActionType) {
  switch(action.type) {
    case 'ADD': {
      return [
        ...state,
        {
          id: state.length+1,
          text: action.listItem!.text,
          state: true
        }
      ]
    }

    case 'DELETE': {
      return state.filter(item => item.id !== action.listItem!.id)
    }

    case 'CHANGE': {
      return state.map(item => {
        if (item.id === action.listItem!.id) {
          return {
            id: item.id,
            text: action.listItem!.text,
            state: action.listItem!.state
          }
        } else {
          return item
        }
      })
    }

    default: {
      throw Error('Unknown action: ' + action.type);
    }
  }
}